<template>
  <div>
    <el-card shadow="hover" class="main-el-card">
      <div ref="chartRef" :style="{ width: '100%', height: '300px' }"></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Request from '@/api/request/request';
import urls from '@/api/request/urls';
import { useEChartsTheme } from '@/api/hooks/useEChartsTheme'; // 导入主题Hook

import * as echarts from 'echarts';
import { dictToMap, getDict } from '@/api/dict';

// 1. 创建ref引用
const chartRef = ref(null);

const xAxisData = ref<string[]>([]);
const seriesData = ref<number[]>([]);

//返回的图表类型接口
interface ChartItem {
  name: string;
  value: number;
}
const chartData = ref<ChartItem[]>([]);

//异步加载数据
const getData = async () => {
  const resData: any = await new Request('/api/backstage/visualize/firstApprovalPassedOrderCountAndOrderCount').get();
  if (resData.success) {
    chartData.value.push({ name: '合格', value: resData.data.firstApprovalPassedOrderCount });
    chartData.value.push({ name: '不合格', value: resData.data.orderCount - resData.data.firstApprovalPassedOrderCount });
  }
};

// 初始化ECharts图表
const initChart = (title: string, themeName: string) => {
  if (chartRef.value) {
    const chart = echarts.init(chartRef.value, themeName);
    chart.setOption({
      title: {
        text: title,
        left: 'center'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      series: [
        {
          name: '整车合格率',
          type: 'pie', //表示饼图
          data: chartData.value,
          label: {
            show: true,
            position: 'outside',
            formatter: function (params: any) {
              // 关键：通过formatter隐藏0值标签
              return params.value === 0 ? '' : params.value; // 值为0时不显示标签
            }
          }
        }
      ]
    });
  }
};

onMounted(async () => {
  // 1. 获取数据
  await getData();
  // 2. 注册主题。两种方法都可以
  const themeName = await useEChartsTheme(new URL(`@/assets/theme/echarts/walden.json`, import.meta.url).href); //放在asserts目录下
  //3.生成图表
  initChart('整车合格情况（首次检测）', themeName);
  console.log(xAxisData.value, seriesData.value);
});
</script>

<style scoped>
/* .main-el-card {
  min-width: 200px;
  overflow: hidden;
  background-color: #64b0f2;
  color: #fff;
} */
</style>
